﻿#include "uifieldsearchwidget.h"
#include "uilineedit.h"
#include <QComboBox>
#include <QLineEdit>
#include <QPushButton>
#include <QLayout>
/**
 * 构造函数：创建一个UI字段搜索小部件。
 * @param parent 父QWidget。
 */
UiFieldSearchWidget::UiFieldSearchWidget(QWidget *parent)
{
    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setStyleSheet("background-color: rgba(0, 0, 0, 0);");

    // 创建字段下拉框
    m_fieldBox = new QComboBox(this);
    m_fieldBox->setMinimumWidth(100);
    connect(m_fieldBox,&QComboBox::currentTextChanged,this,[=](const QString& text){this->search();});

    // 创建搜索文本框
    m_searchEdit = new UiLineEdit(this);
    m_searchEdit->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Preferred);
    connect(m_searchEdit,&UiLineEdit::sigEditFinished,this,[=](){this->search();});
    connect(m_searchEdit,&UiLineEdit::textChanged,this,[=](const QString& text){this->search();});

    // 设置主布局：字段下拉框、搜索文本框、搜索按钮
    QHBoxLayout* mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(0,0,0,0);
    mainLayout->addWidget(m_fieldBox);
    mainLayout->addWidget(m_searchEdit);
}

/**
 * 设置可选字段。
 * @param fields 字段列表。
 */
void UiFieldSearchWidget::setFields(const QStringList &fields)
{
    // 清空字段下拉框，然后添加新字段
    m_fieldBox->clear();
    for(auto f:fields)
    {
        m_fieldBox->addItem(f);
    }
}

void UiFieldSearchWidget::applyFilter(const QString& field, const QString &text)
{
    m_fieldBox->setCurrentText(field);
    m_searchEdit->setText(text);
    emit m_searchEdit->sigEditFinished();
}

void UiFieldSearchWidget::clearSearch()
{
    m_searchEdit->clear();
}

void UiFieldSearchWidget::search()
{
    auto searchText = m_searchEdit->text();
    emit sigSearch(m_fieldBox->currentText(),searchText);
}
